/*
 * 组件注释
 * @Author: machinist_wq
 * @Date: 2022-06-30 20:23:24
 * @LastEditors: machinist_wq
 * @LastEditTime: 2023-03-14 17:19:41
 * @Description: 全局公共函数
 * 人生无常！大肠包小肠......
 */
/// <reference path="./index.d.ts" />
/**
 *
 * @param params 需要判断的参数
 * @returns
 */
export function isEmpty(params: unknown) {
  if (
    params === undefined ||
    params === null ||
    params === "" ||
    (typeof params === "object" && !Object.keys(params).length)
  ) {
    return true;
  }
  return false;
}

/**
 * 因线上部署为二级子目录， 导致接口的路径需内置
 * 这里需要获取配置 path
 * @returns
 */
export function getUrlHref(): string {
  let urlHref = window.location.pathname;
  if (urlHref.indexOf("#")) return "";
  urlHref = urlHref.substring(0, urlHref.length - 1);

  return urlHref;
}

/**
 * 随机数
 * @returns uuid
 */
export const guid = (): string => {
  function S4(): string {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  }

  return (
    S4() +
    S4() +
    "-" +
    S4() +
    "-" +
    S4() +
    "-" +
    S4() +
    "-" +
    S4() +
    S4() +
    S4()
  );
};

/*
 * 获取表格序号
 * @page 页码
 * @pageSize 每页条数
 * @index 第几条
 * */
type NumType = string | number;
export function getTableNumber(page: NumType, pageSize: NumType, idx: number) {
  return (Number(page) - 1) * Number(pageSize) + idx + 1;
}

/*
 * 树形结构
 * @list 原数据
 * idField pidField 映射关系
 * */

function makeTree<T extends {}, K extends keyof T>(
  list: T[],
  idField: K,
  pidField: K
): T[] {
  type other = {
    children?: T[];
  };
  let map: { [key: string]: T } = {};
  list.forEach((e: T) => {
    map[e[idField] as string] = e;
  });

  let roots: T[] = [];
  list.forEach((e: T) => {
    let pid = e[pidField] as string;
    let p = map[pid] as T & other;
    if (p) {
      if (!p.children) {
        let children: T[] | [] = [];
        p.children = children;
      }
      const oldE: T | undefined = (p.children as T[]).find(
        (item: T) => e[idField] === item[idField]
      );
      if (!oldE) {
        p.children.push(e);
      }
    } else {
      (roots as T[]).push(e);
    }
  });
  return roots;
}
/**
 * errorImgSrc图片
 */
const errorImgSrc =
  "";

/**
* 防抖函数
* @param fn 需要防抖的函数
* @param wait 等待时间
* @param immediate 是否立即执行
* @returns
*/
type Fn = { apply: (arg0: any, arg1: IArguments) => void };

const debounce = (fn: Fn, wait?: number, immediate?: boolean): any => {
  let timeout: string | number | NodeJS.Timeout | null | undefined;

  return function (this: any) {
    let args: IArguments = arguments;

    if (timeout) clearTimeout(timeout); // timeout 不为null

    if (immediate) {
      let callNow = !timeout; // 第一次会立即执行，以后只有事件执行后才会再次触发

      timeout = setTimeout(() => (timeout = null), wait || 1000);

      if (callNow) fn.apply(this, args);
    } else {
      timeout = setTimeout(() => fn.apply(this, args), wait || 1000);
    }
  };
};

/**
 * list轮询滚动函数
 * @param scrollBody 滚动的视口
 * @returns timer计数器
 */
const setScrollTop = (scrollBody: Element): ReturnType<typeof setTimeout> => {
  let timer: ReturnType<typeof setTimeout>
  try {
    const scrollHeight = scrollBody.scrollHeight
    const clientHeight = scrollBody.clientHeight
    const loopSetScrollTop = () => {
      if (scrollHeight > clientHeight) {
        timer = setTimeout(() => {
          const oldScrollTop = JSON.parse(JSON.stringify(scrollBody.scrollTop))
          scrollBody.scrollTop += 1
          if (oldScrollTop === scrollBody.scrollTop) {
            scrollBody.scrollTop = 0
          }
          loopSetScrollTop()
        }, 200);
      }
    }
    loopSetScrollTop()
  }
  catch {
    window.clearTimeout(timer!)
  }
  return timer!
}

window.isEmpty = isEmpty;
window.getUrlHref = getUrlHref;
window.guid = guid;
window.getTableNumber = getTableNumber;
window.makeTree = makeTree;
window.errorImgSrc = errorImgSrc;
window.debounce = debounce;
window.setScrollTop = setScrollTop;
